﻿using System;
using System.Windows;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using Indigo.Quibbler.Library;
using System.Diagnostics;
using System.Deployment.Application;
using System.Configuration;
using System.IO;
using Indigo.Quibbler.Common;
using System.ComponentModel;
using Indigo.Quibbler.Data;

namespace Indigo.Quibbler {
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class LoadingWindow : QuibblerWindow {
        private LibManager libManager = new LibManager();
        private DispatcherTimer _loadInitiaterTimer = new DispatcherTimer();
        private EditionWindow _editionWindow = null;
        private string _appId = String.Empty;

        public LoadingWindow() {
            InitializeComponent();
            libManager.DownloadNewsDataComplete += new DownloadDataCompleteHandler(libManager_DownloadDataComplete);
            libManager.DownloadNewsProgressChange += new ProgressChangedEventHandler(libManager_DownloadProgressChange);
            libManager.DownloadPhotoFeedComplete += new DownloadDataCompleteHandler(libManager_DownloadPhotoFeedComplete);
            libManager.DownloadPhotoProgressChange += new ProgressChangedEventHandler(libManager_DownloadPhotoProgressChange);
            libManager.DownloadVideoFeedComplete += new DownloadDataCompleteHandler(libManager_DownloadVideoFeedComplete);
            libManager.DownloadVideoProgressChange += new ProgressChangedEventHandler(libManager_DownloadVideoProgressChange);
            this.Loaded += _LoadingWindow_Loaded;
            this.Closed += _LoadingWindow_Closed;
        }

        #region Handlers
        void _LoadingWindow_Loaded(object sender, RoutedEventArgs e) {
            string applicationType = "MSI";
            #region Register User with Installation ID and Version
            txtVersion.Text = Utilities.GetCurrentVersion();

            string appVersion = String.Empty;
            string versionFilePath = string.Empty;
            versionFilePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"UNRV");
            if (Directory.Exists(versionFilePath) == false) {
                var info = Directory.CreateDirectory(versionFilePath);
                info.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
            }
            if (!versionFilePath.EndsWith(@"\"))
                versionFilePath += @"\";
            versionFilePath += "version.txt";

            if (File.Exists(versionFilePath)) {
                StreamReader streamReader = File.OpenText(versionFilePath);
                appVersion = streamReader.ReadLine();
                streamReader.Close();
                if (!String.IsNullOrEmpty(appVersion)) {
                    _appId = appVersion.Split('/')[0].ToString();
                    appVersion = String.Format("{0}/{1}", _appId, txtVersion.Text);
                }
            }
            if (String.IsNullOrEmpty(appVersion)) {
                _appId = Guid.NewGuid().ToString();
                appVersion = String.Format("{0}/{1}", _appId, txtVersion.Text);
            }
            try {
                StreamWriter streamWriter = File.CreateText(versionFilePath);
                streamWriter.WriteLine(appVersion);
                streamWriter.Close();
            } catch { }
            #endregion

            #region Install Silverlight if Running for First Time
            try {
                if (ConfigurationManager.AppSettings["IsMSISetup"] != null && ConfigurationManager.AppSettings["IsMSISetup"].ToLower().Equals("false")) {
                    applicationType = "ClickOnce";
                    string silverlightRan = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"UNRV");
                    silverlightRan += @"\silverlight.txt";
                    if (File.Exists(silverlightRan) == false) {
                        using (StreamWriter writer = new StreamWriter(silverlightRan)) {
                            writer.Write("done");
                        }
                        string filePath = "Silverlight.exe";
                        Process process = new Process();
                        process.StartInfo = new ProcessStartInfo(filePath);
                        process.StartInfo.Arguments = "/q";
                        process.StartInfo.CreateNoWindow = true;
                        process.Start();
                    }
                }
            } catch { }
            #endregion

            #region Register
            appVersion = appVersion + "/" + applicationType + "/null";
            System.Net.WebClient webClient = new System.Net.WebClient();
            webClient.DownloadDataCompleted += new System.Net.DownloadDataCompletedEventHandler(_webClient_DownloadDataCompleted);
            webClient.DownloadDataAsync(new Uri(String.Format("{0}{1}", ConfigurationSettings.AppSettings["EditionID"], appVersion)));
            #endregion


            Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
            (this.Resources["sbAnimation"] as Storyboard).Begin();

            _loadInitiaterTimer.Interval = TimeSpan.FromMilliseconds(500);
            _loadInitiaterTimer.Tick += new EventHandler(_loadInitiaterTimer_Tick);
            _loadInitiaterTimer.Start();
        }

        void _webClient_DownloadDataCompleted(object sender, System.Net.DownloadDataCompletedEventArgs e) {
        }

        void _LoadingWindow_Closed(object sender, EventArgs e) {
            if (_editionWindow == null || _editionWindow.Visibility != Visibility.Visible)
                Application.Current.Shutdown();
        }

        void _loadInitiaterTimer_Tick(object sender, EventArgs e) {
            _loadInitiaterTimer.Stop();

            // Perform initialization tasks here
            _PerformPostDeploymentTasks();
            _GetAllData();
        }
        #endregion

        #region Private Helper Functions
        private void _GetAllData() {
            string newsData = libManager.GetDownloadedData(libManager.GetPublications()[0].Title, RSSType.News);
            if (String.IsNullOrEmpty(newsData)) {
                /// Step 1/3: Download News articles
                libManager.DownloadNewsDataAsync(libManager.GetPublications()[0].Title, null);
            } else {
                (this.Resources["sbAnimation"] as Storyboard).Stop();
                _editionWindow = new EditionWindow(libManager.GetPublications()[0].Title,
                    libManager.GetDownloadedData(libManager.GetPublications()[0].Title, RSSType.News),
                    libManager.GetDownloadedData(libManager.GetPublications()[0].Title, RSSType.PhotoGallery),
                    libManager.GetDownloadedData(libManager.GetPublications()[0].Title, RSSType.VideoGallery),
                    true, _appId);
                _editionWindow.Show();
                this.Hide();
            }
        }

        private void _PerformPostDeploymentTasks() {
            try {
                // If this is the first run of the application after the deployment/update perform post-deployment tasks as defined in app.config
                if (ApplicationDeployment.IsNetworkDeployed && ApplicationDeployment.CurrentDeployment.IsFirstRun) {
                    Utilities.Log("Performing Post-update tasks...");

                    // Step 1. Clean-up datastore
                    if (_GetDataStoreCleanpConfig()) {
                        Utilities.Log("1. Cleaning data-store");
                        string dataStorePath = Utilities.DataStorePath;
                        if (Directory.Exists(dataStorePath))
                            Directory.Delete(dataStorePath, true);
                    }

                    Utilities.Log("Performing Post-update tasks completed.");
                }
            } catch (Exception ex) {
                Utilities.Log("Error in Performing Post-Deployment Tasks: ", ex);
            }
        }

        private static bool _GetDataStoreCleanpConfig() {
            try { return bool.Parse(ConfigurationSettings.AppSettings["AutoUpdate.FirstRun.CleanDataStore"]); } catch { }

            return false;
        }
        #endregion

        #region Event Handlers
        void libManager_DownloadProgressChange(object sender, ProgressChangedEventArgs e) {
            txtStatus.Text = "Downloading News: " + e.ProgressPercentage.ToString() + " %";
        }

        void libManager_DownloadPhotoProgressChange(object sender, ProgressChangedEventArgs e) {
            txtStatus.Text = "Downloading Photos (metadata): " + e.ProgressPercentage.ToString() + " %";
        }

        void libManager_DownloadVideoProgressChange(object sender, ProgressChangedEventArgs e) {
            txtStatus.Text = "Downloading Video (metadata): " + e.ProgressPercentage.ToString() + " %";
        }

        void libManager_DownloadDataComplete(object sender, DownloadCompleteEventArgs e) {
            if (e.Error == null) {
                /// Step 2/3: Download Photos metadata
                libManager.DownloadPhotoFeedAsync(libManager.GetPublications()[0].Title, null);
            } else {
                (this.Resources["sbAnimation"] as Storyboard).Stop();
                MessageBox.Show("Could not connect to news server. \r\nPlease check your internet connection and try again later.",
                    "Connection error.", MessageBoxButton.OK, MessageBoxImage.Error);
                Utilities.Log("Error in Downloading News: ", e.Error);
                Application.Current.Shutdown();
            }
        }

        void libManager_DownloadPhotoFeedComplete(object sender, DownloadCompleteEventArgs e) {
            if (e.Error != null)
                Utilities.Log("Error in Downloading Photos metadata: ", e.Error);

            /// Step 3/3: Download Videos metadata
            libManager.DownloadVideoFeedAsync(libManager.GetPublications()[0].Title, null);
        }

        void libManager_DownloadVideoFeedComplete(object sender, DownloadCompleteEventArgs e) {
            (this.Resources["sbAnimation"] as Storyboard).Stop();
            if (e.Error != null)
                Utilities.Log("Error in Downloading Videos metadata: ", e.Error);

            string newsFeed = libManager.GetDownloadedData(libManager.GetPublications()[0].Title, RSSType.News);
            string photosFeed = libManager.GetDownloadedData(libManager.GetPublications()[0].Title, RSSType.PhotoGallery);
            string videosFeed = libManager.GetDownloadedData(libManager.GetPublications()[0].Title, RSSType.VideoGallery);
            Parser.RefreshXmlDoc(ContentType.News, newsFeed);
            Parser.RefreshXmlDoc(ContentType.Photo, photosFeed);
            Parser.RefreshXmlDoc(ContentType.Video, videosFeed);

            _editionWindow = new EditionWindow(libManager.GetPublications()[0].Title,
                    newsFeed, photosFeed, videosFeed, true, _appId);
            _editionWindow.Show();
            this.Hide();
        }
        #endregion
    }
}
